using FytSoa.Domain.Cms;
using FytSoa.Sugar;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using AutoMapper;
using FytSoa.Common.Utils;
using FytSoa.Domain.Core.Param;
using FytSoa.Domain.Core.Result;
using Masuit.Tools.Linq;
using Microsoft.AspNetCore.Mvc;

namespace FytSoa.Application.Cms
{
    /// <summary>
    /// 文章表 服务接口
    /// </summary>
    [ApiExplorerSettings(GroupName = "v2")]
    public class CmsArticleService : SugarRepository<CmsArticle>,ICmsArticleService 
    {
        private readonly IMapper _mapper;
        public CmsArticleService(IMapper mapper)
        {
            _mapper = mapper;
        }
        
        /// <summary>
        /// 查询所有——分页
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public async Task<ApiResult<PageResult<CmsArticleDto>>> GetPagesAsync(PageParam<ArticleParam> param)
        {
            Expression<Func<CmsArticle, bool>> where = m => true;
            var whereStr = "1=1";
            if (param.Filter.Recycle && param.Filter.Attr != 5) {
                where.And (m => m.Attr.Contains (5));
                whereStr += " and locate('5',attr)>0";
            }
            if (!param.Filter.Recycle && param.Filter.Attr != 5) {
                where.And (m => !m.Attr.Contains (5));
                whereStr += " and locate('5',attr)=0";
            }
            if (!string.IsNullOrEmpty (param.Filter.Key)) {
                where.And (m => m.Title.Contains (param.Filter.Key) || m.KeyWord.Contains (param.Filter.Key) || m.SubTitle.Contains (param.Filter.Key) || m.Summary.Contains (param.Filter.Key) || m.Author.Contains (param.Filter.Key) || m.Source.Contains (param.Filter.Key) || m.Tag.Equals (param.Filter.Key));
                whereStr += " and locate('" + param.Filter.Key + "',title)>0";
            }
            if (param.Filter.Id != 0) {
                where.And (m => m.ColumnId == param.Filter.Id);
                whereStr += " and columnId=" + param.Filter.Id;
            }
            if (param.Filter.Status == "1") {
                where.And (m => m.Status);
                whereStr += " and status=true";
            }
            if (param.Filter.Status == "2") {
                where.And (m => !m.Status);
                whereStr += " and status=false";
            }
            if (param.Filter.Attr != 0) {
                where.And (m => m.Attr.Contains (param.Filter.Attr));
                whereStr += " and locate('" + param.Filter.Attr + "',attr)>0";
            }
            if (param.Filter.ColumnList.Count>0)
            {
                whereStr += " and locate(columnId,'" + string.Join(",", param.Filter.ColumnList.ToArray()) + "')>0";
            }
            var (list,totalItems,totalPage) = await base.GetPageResultAsync(where, param.Page, param.Limit, m => m.Id);
            var result = new PageResult<CmsArticleDto>()
            {
                Items = _mapper.Map<List<CmsArticleDto>>(list),
                TotalItems = totalItems,
                TotalPages = totalPage
            };
            return JResult<PageResult<CmsArticleDto>>.Success(result);
        }

        /// <summary>
        /// 根据主键查询
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ApiResult<CmsArticleDto>> GetAsync(long id)
        {
            return JResult<CmsArticleDto>.Success(_mapper.Map<CmsArticleDto>(await base.GetByIdAsync(id)));
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> AddAsync(CmsArticleDto model)
        {
            return JResult<bool>.Success(await base.InsertAsync(_mapper.Map<CmsArticle>(model)));
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> ModifyAsync(CmsArticleDto model)
        {
            return JResult<bool>.Success(await base.UpdateAsync(_mapper.Map<CmsArticle>(model)));
        }

        /// <summary>
        /// 添加到回收站
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        public async Task<ApiResult<bool>> Recycle(string ids)
        {
            var list = await base.GetListAsync (m => ids.StrToListLong ().Contains (m.Id));
            list.ForEach (m => {
                m.Attr.Add(5);
            });
            return JResult<bool>.Success(await base.UpdateRangeAsync(list));
        }

        /// <summary>
        /// 删除,支持多个
        /// </summary>
        /// <param name="ids">逗号分隔</param>
        /// <returns></returns>
        public async Task<ApiResult<bool>> DeleteAsync(string ids)
        {
            var id = ids.StrToListLong();
            return JResult<bool>.Success(await base.DeleteAsync(m=>id.Contains(m.Id)));
        }

        /// <summary>
        /// 复制或转移操作
        /// </summary>
        /// <returns></returns>
        [HttpPut]
        public async Task<ApiResult<bool>> CopyTransfer(ArticleCopyParam param)
        {
            var list = await base.GetListAsync (m => param.ArticleIds.StrToListLong ().Contains (m.Id));
            if (param.Type == 1) {
                //copy
                list.ForEach (m => {
                    m.Id = Unique.Id ();
                    m.ColumnId = param.ColumnId;
                });
                return JResult<bool>.Success (await base.InsertRangeAsync(list));
            }
            list.ForEach (m => {
                m.ColumnId = param.ColumnId;
            });
            return JResult<bool>.Success (await base.UpdateRangeAsync(list));
        }
    }
}
